<template>
  <el-dialog :title="'移库'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">
      <el-form-item label="所属公司" prop="companyId">
        <el-select v-model="dataForm.companyId" placeholder="请选择" @change="companyChange">
          <el-option
            v-for="item in companys"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出货店铺" prop="outShopId">
        <el-select v-model="dataForm.outShopId" placeholder="请选择" @change="shopChange">
          <el-option v-for="item in shops" :key="item.id" :label="item.shopName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入货店铺" prop="inShopId">
        <el-select v-model="dataForm.inShopId" placeholder="请选择" @change="shopChange">
          <el-option v-for="item in shops" :key="item.id" :label="item.shopName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品">
        <el-row>
          <el-button type="primary" @click="addGoodsHandle()">添加商品</el-button>
        </el-row>
        <el-row>
          <el-table
            :data="dataForm.goodsList"
            border
            style="width: 100%;"
            :header-cell-style="{ background: '#17b3a3', color: '#fff' }"
          >
            <el-table-column prop="goodsName" header-align="center" align="center" label="商品名称"></el-table-column>
            <el-table-column prop="catName" header-align="center" align="center" label="商品类型"></el-table-column>
            <!-- <el-table-column prop="goodsPrice" header-align="center" align="center" label="单价"></el-table-column> -->
            <el-table-column header-align="center" align="center" label="数量">
              <template slot-scope="{ row }">
                <el-input v-model="row.num" :change="handleInput(row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="deleteGoods(scope.$index)">X</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="disabled" @click="dataFormSubmit()">确定</el-button>
    </span>
    <!-- 添加商品弹窗 -->
    <GoodsAdd
      ref="goodsAdd"
      v-if="goodsAddVisible"
      :companyId="dataForm.companyId"
      :shopId="dataForm.outShopId"
      @add-goods-callback="addGoodsCallback"
      @cancel="addGoodsCancel"
    ></GoodsAdd>
  </el-dialog>
</template>

<script>
import { getShopsByCompany } from "@/utils";

import GoodsAdd from "./goods-add";
export default {
  props: {
    companys: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  components: {
    GoodsAdd
  },
  data() {
    return {
      visible: false,
      disabled: false,
      goodsAddVisible: false,
      dataForm: {
        id: null,
        companyId: null,
        outShopId: null,
        inShopId: null,
        depotId: null,
        type: 3,
        createTime: null,
        verifyTime: null,
        status: null,
        goodsList: []
      },
      shops: [],
      dataRule: {
        companyId: [{ required: true, message: "请选择公司", trigger: "blur" }],
        outShopId: [
          { required: true, message: "请选择出货店铺", trigger: "blur" }
        ],
        inShopId: [
          { required: true, message: "请选择入货店铺", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    init() {
      this.dataForm = {
        id: null,
        companyId: null,
        outShopId: null,
        inShopId: null,
        depotId: null,
        type: 3,
        createTime: null,
        verifyTime: null,
        status: null,
        goodsList: []
      };
      this.shops = [];
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
    },
    // 添加商品弹窗
    addGoodsHandle() {
      if (this.dataForm.outShopId == null || this.dataForm.inShopId == null) {
        this.$message.error("请选择出货店铺和入货店铺");
        return;
      }
      if (this.dataForm.outShopId == this.dataForm.inShopId) {
        this.$message.error("出货店铺和入货店铺不能是同一个");
        return;
      }
      this.goodsAddVisible = true;
      this.$nextTick(() => {
        this.$refs.goodsAdd.init();
      });
    },
    // 公司选择事件
    companyChange(companyId) {
      this.dataForm.goodsList = []
      this.dataForm.inShopId = null;
      this.dataForm.outShopId = null;
      getShopsByCompany(companyId, res => {
        this.shops = res;
      });
    },
    shopChange(shopId) {
      this.dataForm.goodsList = []
    },
    // 添加商品弹窗取消
    addGoodsCancel() {
      this.goodsAddVisible = false;
    },
    // 添加商品回调
    addGoodsCallback(goodsList) {
      if (!goodsList || goodsList.length == 0) {
        return;
      }
      goodsList.forEach(goods => {
        let flag = false;
        this.dataForm.goodsList.forEach(item => {
          if (goods.id == item.id) {
            flag = true;
            return false;
          }
        });
        if (flag) {
          return false;
        }
        this.$set(goods, "num", 1);
        this.$set(goods, "edit", true);
        this.dataForm.goodsList.push(goods);
      });
      this.goodsAddVisible = false;
    },
    // 删除商品
    deleteGoods(index) {
      this.dataForm.goodsList.splice(index, 1);
    },
    // 数字输入检查
    handleInput(row) {
      var num = row.num + "";
      num = num.replace(/[^\d]/g, ""); // 清除“数字”和“.”以外的字符
      if (num.indexOf(".") < 0 && num != "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        num = parseInt(num);
      } else if (num == "" || num == undefined || num == null) {
        num = 0;
      }
      row.num = num;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.dataForm.goodsList.length == 0) {
            this.$message.error("请添加商品");
            return;
          }
          this.disabled = true;
          this.$http({
            url: this.$http.adornUrl(`/merchant/shop/stock/applyForm/save`),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              companyId: this.dataForm.companyId,
              outShopId: this.dataForm.outShopId,
              inShopId: this.dataForm.inShopId,
              type: this.dataForm.type,
              goodsList: this.dataForm.goodsList
            })
          }).then(({ data }) => {
            this.disabled = false;
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
